package com.adam.example.aggregation.metric;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.DistanceUnit;
import co.elastic.clients.elasticsearch._types.LatLonGeoLocation;
import co.elastic.clients.elasticsearch._types.TopLeftBottomRightGeoBounds;
import co.elastic.clients.elasticsearch._types.aggregations.*;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import com.adam.example.ElasticsearchClientHolder;
import com.adam.example.util.JsonUtil;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class GeoBoundsAggregationExample {

    public static void main(String[] args) throws IOException {
        ElasticsearchClient elasticsearchClient = ElasticsearchClientHolder.getINSTANCE().initializeAndGetClient();

        SearchRequest searchRequest = SearchRequest.of(builder -> builder
                        .index("test_geo_point")
                        .size(0)
                        .aggregations("agg", aggregationBuilder -> aggregationBuilder
                                .geoBounds(geoBoundsAggregationBuilder -> geoBoundsAggregationBuilder
                                        .field("location")
                                )
                        )
        );
        System.out.println(JsonUtil.searchRequestToJson(searchRequest, elasticsearchClient));
        SearchResponse<Void> searchResponse = elasticsearchClient.search(searchRequest, Void.class);
        Aggregate aggregate = searchResponse.aggregations().get("agg");
        GeoBoundsAggregate geoBoundsAggregate = aggregate.geoBounds();
        TopLeftBottomRightGeoBounds topLeftBottomRightGeoBounds = geoBoundsAggregate.bounds().tlbr();
        LatLonGeoLocation topLeftLocation = topLeftBottomRightGeoBounds.topLeft().latlon(),
                bottomRightLocation = topLeftBottomRightGeoBounds.bottomRight().latlon();
        System.out.println("topLeft:[" + topLeftLocation.lat() + "," + topLeftLocation.lon() + "],bottomRight:["
                + bottomRightLocation.lat() + "," + bottomRightLocation.lon() + "]");

        ElasticsearchClientHolder.getINSTANCE().close();
    }

}
